<?php

/**
 * @file
 * Fetch specified items from multiple.
 */

$plugin = array(
  'form' => 'feeds_tamper_ccloud_fetch_specified_items_form',
  'callback' => 'feeds_tamper_ccloud_fetch_specified_items_callback',
  'name' => 'CCloud: Fetch specified item(s)',
  'multi' => 'direct',
  'category' => 'HTML',
);

function feeds_tamper_ccloud_fetch_specified_items_form($importer, $element_key, $settings) {
  $form = array();

  $form['indexes'] = array(
    '#type' => 'textfield',
    '#title' => t('Indexes'),
    '#required' => TRUE,
    '#description' => t('Separated by commas, such as: 0,1,2'),
    '#default_value' => isset($settings['indexes']) ? $settings['indexes'] : 0,
  );

  $form['return_string'] = array(
    '#type' => 'checkbox',
    '#title' => t('Return as a string (if only 1 item)'),
    '#default_value' => isset($settings['return_string']) ? $settings['return_string'] : TRUE,
  );

  return $form;
}

function feeds_tamper_ccloud_fetch_specified_items_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  if(is_array($field)) {
    $indexes = $settings['indexes'];
    $indexes_array = explode(',', $indexes);

    $field_new = array();

    foreach ($indexes_array as $index) {
      if (!empty($field[$index])) {
        $field_new[] = $field[$index];
      }
    }

    if(count($field_new) === 1 && !empty($settings['return_string'])) {
      $field_new = $field_new[0];
    }

    $field = $field_new;
  }
}